const { Op } = require('sequelize');
const Man = require('../entity/Man')

async function saveMan(req) {
    try {
        const {id, name, sex, age, work, salary,phone} = req.body;
        console.log(name)
        const existingMan = await Man.findOne({where: {id: id}});
        if (existingMan) {
            // 如果存在，则执行更新操作
            const updatedMan = await Man.update({
                name: name,
                age: age,
                sex: sex,
                work: work,
                salary: salary,
                phone: phone
            }, {
                where: {id: id}
            });
            return updatedMan;
        } else {
            // 如果不存在，则执行插入操作
            const newMan = await Man.create({
                name: name,
                age: age,
                sex: sex,
                work: work,
                salary: salary,
                phone: phone
            });
            return newMan;
        }
    } catch (error) {
        console.error('创建员工时出错:', error);
    }
}

async function findPage(req) {
    try{
        const {pageNum, pageSize, searchName, searchId} = req.query;
        const pageNumInt = parseInt(pageNum);
        const pageSizeInt = parseInt(pageSize);

        const offset = (pageNumInt - 1) * pageSizeInt; // 计算偏移量
        // 查询数据库获取总记录数
        let queryOptions = {
            offset,
            limit: pageSizeInt, // 使用 limit 控制返回的行数
        };
        queryOptions.where = {};
        if (searchName !== undefined && searchName !== '') {
            queryOptions.where.name = {
                [Op.like]: `%${searchName}%`
            };
        }
        if (searchId !== undefined && searchId !== '') {
            queryOptions.where.id = {
                [Op.like]: `%${searchId}%`
            };
        }
        // 查询数据库获取总记录数
        const totalCount = await Man.count(queryOptions);
        queryOptions.attributes=['id','name','sex','age','work','salary','phone'];

        queryOptions.group = ['id', 'name', 'sex', 'age', 'work', 'salary','phone'];
        const mans = await Man.findAll(queryOptions);
        return {
            totalCount, mans
        };
    }catch (error) {
        throw error;
    }

}
async function deleteMan(req) {
    try{
        const {id}=req.params;
        const deletedRows = await Man.destroy({
            where: {
                id: id
            }
        })
        if (deletedRows > 0) {
            console.log(`成功删除了 ${deletedRows} 条记录`);
        } else {
            throw new Error('未找到匹配的记录');
        }
    }catch(error) {
        throw error;
    }
}
async function batchMan(items) {
    try {
        // 删除数据库中对应多个ID的菜品
        const deletedRows = await Man.destroy({
            where: {
                id: items // 使用数组形式传递所有要删除的菜品的 id
            }
        });

        if (deletedRows > 0) {
            console.log(`成功删除了 ${deletedRows} 条记录`);
            // 可选择返回一个删除成功的消息
            return {message: '批量删除成功'};
        } else {
            console.log('未找到匹配的记录');
            throw new Error('未找到匹配的记录');
        }
    } catch (error) {
        // 处理错误
        console.error("Error delete dish:", error);
        throw error;
    }
}
module.exports = {
    saveMan, findPage,deleteMan,batchMan
};